package com.coolsummer.limiter;

import com.coolsummer.abstracts.Limiter;
import com.coolsummer.utils.DateUtil;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author coolsummer
 * @describe 计数器算法
 * @date 2019/11/18 15:41
 */
public class CountLimiter extends Limiter{
    /**
     * 系统当前时间
     */
    private long counterTime;
    /**
     * 限流的时间段（毫秒）
     */
    private final long SEGMENT = 1000;
    /**
     * 请求的个数
     */
    private AtomicInteger requestNumber = new AtomicInteger(0);

    public CountLimiter(double qps) {
        super(qps);
        counterTime = DateUtil.getCounterTime();
    }

    @Override
    public synchronized boolean tryAcquire(){
        long now = DateUtil.getCounterTime();
        if(now < counterTime + SEGMENT){
            if(requestNumber.get() < qps){
                requestNumber.incrementAndGet();
                return true;
            } else {
                return false;
            }
        } else {
            counterTime = DateUtil.getCounterTime()>>3<<3;
            requestNumber.set(1);
            return true;
        }
    }
}
